package com.zhang.zhangapp.utils;

import android.app.Activity;

import java.util.Stack;

/**
 * Created by 罗肖 on 2017/4/25.
 */
public class ActivityManager {

    private static Stack<Activity> activityStack = new Stack<Activity>();

    private static ActivityManager instance;

    private ActivityManager() {

    }

    public static ActivityManager getActivityManager() {
        if (instance == null)
            instance = new ActivityManager();
        return instance;
    }

    /**
     * 添加Activity到栈
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activityStack.add(activity);
    }

    /**
     * 获取最后一个加入的Activity
     *
     * @return
     */
    public Activity getCurrentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 结束activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }


    /**
     * 结束activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity = null;
        }
    }



    /**
     * 结束指定类名Activity
     *
     * @param cls
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls))
                finishActivity(activity);
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0; i < activityStack.size(); i++) {
            if (null != activityStack.get(i))
                activityStack.get(i).finish();
        }
        activityStack.clear();
    }

    public Activity getActivty(Class<?> cls){
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls))
                return activity;
        }
        return  null;
    }

    /**
     * 退出APP
     */
    public void AppExit() {
        try {
            finishAllActivity();
            System.exit(0);
        } catch (Exception e) {
        }
    }

}
